﻿
namespace CoProjectDF.Repository
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using CoProjectModel;
    using IdeaBlade.Application.Framework.Core.Persistence;
    using IdeaBlade.EntityModel;
    using IdeaBlade.Linq;

    [Export(typeof(IToDoListRepository))]
    public class ToDoListRepository : IToDoListRepository
    {
        [ImportingConstructor]
        public ToDoListRepository(IEntityManagerProvider<CoProjectEntities> entityManagerProvider)
        {
            EntityManagerProvider = entityManagerProvider;
        }

        public INotifyCompleted Initialise()
        {
            return EntityManagerProvider.InitializeAsync();
        }

        public INotifyCompleted GetToDoLists(string orderByToListName, Action<IEnumerable<ToDoList>> onSuccess = null,
                                                                       Action<Exception> onFail = null)
        {
            IEntityQuery<ToDoList> query = Manager.ToDoLists;
            if (orderByToListName != null)
            {
                var selector = new SortSelector(typeof(ToDoList), orderByToListName);
                query = query.OrderBySelector(selector);
            }

            EntityQueryOperation<ToDoList> op = query.ExecuteAsync();
            return op.OnComplete(onSuccess, onFail);
        }

        public INotifyCompleted FindToDoListByName(string name, Action<IEnumerable<ToDoList>> onSuccess, Action<Exception> onFail)
        {
            var q = Manager.ToDoLists.Where(c => c.Name == name);
            var op = q.ExecuteAsync();
            return op.OnComplete(onSuccess, onFail);
        }

        private IEntityManagerProvider<CoProjectEntities> EntityManagerProvider { get; set; }
        private CoProjectEntities Manager { get { return EntityManagerProvider.Manager; } }

    }
}
